#!/usr/bin/env python3
"""
新易访内网系统 - FastAPI 主应用
"""

import logging
from contextlib import asynccontextmanager
from collections.abc import AsyncGenerator

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.core.config import settings
from app.database.session import engine
from app.models import Base
from app.routes import audit, auth, dashboard, qrcode, system, visitors

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[logging.FileHandler("app.log"), logging.StreamHandler()],
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """应用生命周期管理"""
    # 启动时
    logger.info("启动新易访内网系统...")

    # 创建数据库表
    try:
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)  # type: ignore[attr-defined]
        logger.info("数据库表创建成功")
    except Exception as e:
        logger.error(f"数据库表创建失败: {e}")
        raise

    yield

    # 关闭时
    logger.info("关闭新易访内网系统...")
    await engine.dispose()


app = FastAPI(
    title="新易访内网系统",
    description="访客管理内网核验系统API",
    version="1.0.0",
    lifespan=lifespan,
    docs_url="/docs",
    redoc_url="/redoc",
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
app.include_router(dashboard.router, prefix="/api/dashboard", tags=["dashboard"])
app.include_router(visitors.router, prefix="/api/visitors", tags=["visitors"])
app.include_router(audit.router, prefix="/api/audit", tags=["audit"])
app.include_router(qrcode.router, prefix="/api/qrcode", tags=["qrcode"])
app.include_router(system.router, prefix="/api/system", tags=["system"])


@app.get("/")
async def root() -> dict[str, str]:
    """根端点"""
    return {"message": "新易访内网系统API", "version": "1.0.0", "docs": "/docs"}


@app.get("/health")
async def health_check() -> dict[str, str]:
    """健康检查"""
    return {"status": "healthy"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host=settings.HOST, port=settings.PORT, reload=settings.DEBUG)
